package com.fary.boot.reactor;

import com.fary.boot.SpringApplication;
import com.fary.boot.env.EnvironmentPostProcessor;
import com.fary.core.Ordered;
import com.fary.core.env.ConfigurableEnvironment;
import com.fary.util.ClassUtils;

public class DebugAgentEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {

    private static final String REACTOR_DEBUGAGENT_CLASS = "reactor.tools.agent.ReactorDebugAgent";

    private static final String DEBUGAGENT_ENABLED_CONFIG_KEY = "spring.reactor.debug-agent.enabled";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        if (ClassUtils.isPresent(REACTOR_DEBUGAGENT_CLASS, null)) {
            Boolean agentEnabled = environment.getProperty(DEBUGAGENT_ENABLED_CONFIG_KEY, Boolean.class);
            if (agentEnabled != Boolean.FALSE) {
                try {
                    Class<?> debugAgent = Class.forName(REACTOR_DEBUGAGENT_CLASS);
                    debugAgent.getMethod("init").invoke(null);
                } catch (Exception ex) {
                    throw new RuntimeException("Failed to init Reactor's debug agent", ex);
                }
            }
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

}